# Windows安装脚本

# 检查管理员权限
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-Error "请以管理员权限运行此脚本"
    exit 1
}

# 创建目录
$basePath = "C:\live-platform"
$paths = @(
    "$basePath\uploads",
    "$basePath\logs",
    "$basePath\logs\nginx",
    "$basePath\logs\pm2",
    "$basePath\streams",
    "$basePath\client"
)

foreach ($path in $paths) {
    if (-not (Test-Path $path)) {
        New-Item -ItemType Directory -Path $path
    }
}

# 安装Node.js
$nodeVersion = "16.14.2"
$nodePath = "$env:ProgramFiles\nodejs"
if (-not (Test-Path $nodePath)) {
    Write-Host "正在安装Node.js..."
    $nodeUrl = "https://npm.taobao.org/mirrors/node/v$nodeVersion/node-v$nodeVersion-x64.msi"
    $nodeInstaller = "$env:TEMP\node-installer.msi"
    Invoke-WebRequest -Uri $nodeUrl -OutFile $nodeInstaller
    Start-Process msiexec.exe -Wait -ArgumentList "/i $nodeInstaller /quiet"
    Remove-Item $nodeInstaller
}

# 安装全局依赖
npm config set registry https://registry.npmmirror.com
npm install -g pm2 typescript

# 安装MySQL
$mysqlVersion = "8.0.28"
if (-not (Get-Service -Name "MySQL80" -ErrorAction SilentlyContinue)) {
    Write-Host "正在安装MySQL..."
    $mysqlUrl = "https://mirrors.aliyun.com/mysql/MySQL-8.0/mysql-$mysqlVersion-winx64.zip"
    $mysqlZip = "$env:TEMP\mysql.zip"
    Invoke-WebRequest -Uri $mysqlUrl -OutFile $mysqlZip
    Expand-Archive $mysqlZip -DestinationPath "C:\mysql"
    Remove-Item $mysqlZip
    
    # 配置MySQL
    Copy-Item "deploy\config\my.ini" "C:\mysql\my.ini"
    & "C:\mysql\bin\mysqld.exe" --initialize-insecure
    & "C:\mysql\bin\mysqld.exe" --install
    Start-Service MySQL80
}

# 安装Redis
$redisVersion = "5.0.14"
if (-not (Get-Service -Name "Redis" -ErrorAction SilentlyContinue)) {
    Write-Host "正在安装Redis..."
    $redisUrl = "https://github.com/tporadowski/redis/releases/download/v$redisVersion/Redis-x64-$redisVersion.msi"
    $redisInstaller = "$env:TEMP\redis-installer.msi"
    Invoke-WebRequest -Uri $redisUrl -OutFile $redisInstaller
    Start-Process msiexec.exe -Wait -ArgumentList "/i $redisInstaller /quiet"
    Remove-Item $redisInstaller
}

# 安装Nginx
$nginxVersion = "1.20.2"
if (-not (Test-Path "C:\nginx")) {
    Write-Host "正在安装Nginx..."
    $nginxUrl = "http://nginx.org/download/nginx-$nginxVersion.zip"
    $nginxZip = "$env:TEMP\nginx.zip"
    Invoke-WebRequest -Uri $nginxUrl -OutFile $nginxZip
    Expand-Archive $nginxZip -DestinationPath "C:\"
    Remove-Item $nginxZip
    Rename-Item "C:\nginx-$nginxVersion" "C:\nginx"
    
    # 配置Nginx
    Copy-Item "deploy\config\nginx.conf" "C:\nginx\conf\nginx.conf"
}

Write-Host "安装完成!" 